using System;
using System.Collections.Generic;
using System.Text.Json;
using JlPay.Sdk.Core;
using JlPay.Sdk.Services;
using System.Linq; // Added for Take()

namespace JlPay.Sdk.Models.BaseData
{
    /// <summary>
    /// 银行总行信息查询响应
    /// </summary>
    public class BankListResponse : StandardResponse, IComplexFieldHandler
    {
        /// <summary>
        /// 每页记录数
        /// </summary>
        public int? Limit { get; set; }

        /// <summary>
        /// 偏移量
        /// </summary>
        public int? Offset { get; set; }

        /// <summary>
        /// 总记录数
        /// </summary>
        public int? Total { get; set; }

        /// <summary>
        /// 数据
        /// </summary>
        public List<Dictionary<string, object>>? Data { get; set; }

        /// <summary>
        /// 处理复杂字段，专门处理Data字段的解析
        /// </summary>
        /// <param name="fieldName">字段名</param>
        /// <param name="fieldValue">字段值</param>
        public void HandleComplexField(string fieldName, object fieldValue)
        {
            if (fieldName.ToLower() == "data" && fieldValue != null)
            {
                try
                {
                    if (fieldValue is List<Dictionary<string, object>> listValue)
                    {
                        Data = listValue;
                    }
                    else if (fieldValue is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Array)
                    {
                        var list = new List<Dictionary<string, object>>();
                        foreach (var item in jsonElement.EnumerateArray())
                        {
                            if (item.ValueKind == JsonValueKind.Object)
                            {
                                var dict = new Dictionary<string, object>();
                                foreach (var jsonProp in item.EnumerateObject())
                                {
                                    // 使用GetString()方法获取字符串值，避免保留JSON格式的引号
                                    if (jsonProp.Value.ValueKind == JsonValueKind.String)
                                    {
                                        dict[jsonProp.Name] = jsonProp.Value.GetString();
                                    }
                                    else
                                    {
                                        // 对于非字符串类型，使用GetRawText()保持原始格式
                                        dict[jsonProp.Name] = jsonProp.Value.GetRawText();
                                    }
                                }
                                list.Add(dict);
                            }
                        }
                        Data = list;
                    }
                    else if (fieldValue is string stringValue)
                    {
                        try
                        {
                            var parsed = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(stringValue);
                            Data = parsed;
                        }
                        catch
                        {
                            // 解析失败，设置为空列表
                            Data = new List<Dictionary<string, object>>();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"解析Data字段时出错: {ex.Message}");
                    Data = new List<Dictionary<string, object>>();
                }
            }
        }

        /// <summary>
        /// 重写HandleResponse方法，确保响应报文格式完全符合预期
        /// </summary>
        /// <param name="operationName">操作名称</param>
        /// <param name="config">配置对象</param>
        public new void HandleResponse(string operationName, Config? config = null)
        {
            if (IsSuccess())
            {
                Console.WriteLine($"{operationName}成功！");
                
                // 手动构建响应JSON，确保字段名称和结构完全符合预期
                var responseData = new Dictionary<string, object>
                {
                    ["ret_code"] = RetCode ?? "",
                    ["ret_msg"] = RetMsg ?? "",
                    ["limit"] = Limit ?? 0,
                    ["offset"] = Offset ?? 0,
                    ["total"] = Total ?? 0,
                    ["data"] = Data ?? new List<Dictionary<string, object>>()
                };
                
                Console.WriteLine("响应报文：" + JsonSerializer.Serialize(responseData, new JsonSerializerOptions 
                { 
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                }));
            }
            else
            {
                Console.WriteLine($"{operationName}失败: {RetCode} - {RetMsg}");
            }
        }
    }
} 